# -*- coding: utf-8 -*-
"""
USB摄像头模块
"""
import cv2
import time
from src.config import CAMERA_CONFIG


class USBCamera:
    def __init__(self):
        """初始化USB摄像头"""
        # 从config.py读取配置，这些参数已写死但可通过配置文件修改
        self.device_id = CAMERA_CONFIG['device_id']
        self.frame_width = CAMERA_CONFIG['frame_width']
        self.frame_height = CAMERA_CONFIG['frame_height']
        self.fps = CAMERA_CONFIG['fps']

        # 初始化摄像头
        self.cap = None
        self._initialize_camera()

    def _initialize_camera(self):
        """初始化摄像头设备"""
        try:
            self.cap = cv2.VideoCapture(self.device_id)
            self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.frame_width)
            self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.frame_height)
            self.cap.set(cv2.CAP_PROP_FPS, self.fps)

            # 测试摄像头是否正常工作
            if not self.cap.isOpened():
                raise Exception("无法打开摄像头设备")

            print(f"USB摄像头初始化成功: {self.frame_width}x{self.frame_height} @ {self.fps}FPS")

        except Exception as e:
            print(f"摄像头初始化失败: {e}")
            raise

    def read_frame(self):
        """
        从摄像头读取一帧图像

        返回:
            ret: 读取是否成功 (True/False)
            frame: 图像帧 (BGR格式)
        """
        if self.cap is None:
            return False, None

        ret, frame = self.cap.read()
        return ret, frame

    def release(self):
        """释放摄像头资源"""
        if self.cap is not None:
            self.cap.release()
            print("摄像头资源已释放")